<?php

namespace app\api\controller\type;

use think\Controller;

class Type extends Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->TypeModel = model('Product.Type');
        $this->ProductModel = model('Product.Product');
        $this->UserModel = model('User.User');
        $this->VipModel = model('Product.Vip');
        $this->CartModel = model('Cart');
    }
    // 分类首页
    public function index()
    {
        if ($this->request->isPost()) {
            // 商品分类
            $producttype = $this->TypeModel->select();
            $typelist = [];
            foreach ($producttype as $item) {
                $typelist[] = ['text' => $item['name']];
            }
            // 商品表
            $productlist = $this->ProductModel->with('type')->order('id', 'desc')->select();
            $datalist = [];
            // 实时推荐
            $recommend = [];
            foreach ($productlist as $item) {
                $item['flag'] == 1 ? $item['flag'] = '新品' : ($item['flag'] == 2 ? $item['flag'] = '热销' : ($item['flag'] == 3 ? $item['flag'] = '推荐' : "flag$item[flag]"));
                // 商品类别
                isset($datalist[$item['typeid']]) ? $datalist[$item['typeid']][] = ['name'=>$item['name'], 'cover'=>$item['covercdn']] : $datalist[$item['typeid']] = [['name'=>$item['name'], 'cover'=>$item['covercdn']]];
                // 商品状态
                // isset($datalist[$item['typeid']][$item['flag']]) ? $datalist[$item['typeid']][$item['flag']][] = [$item['name'], $item['covercdn']] : $datalist[$item['typeid']][$item['flag']] = [[$item['name'], $item['covercdn']]];
                // 商品实时分类推荐
                isset($recommend[$item['flag']]) ? $recommend[$item['flag']][] = ['cover'=>$item['covercdn'],'typename'=>$item['type']['name']] : $recommend[$item['flag']] = [['cover'=>$item['covercdn'],'typename'=>$item['type']['name']]];
            }
            $data = [
                'datalist' => $datalist,
                'typelist' => $typelist,
                'toplist' => array_slice($productlist,0,3),
                'recommend' => isset($recommend['推荐']) ? array_slice($recommend['推荐'], 0, 9) : [],
            ];

            $this->success('ok', null, $data);
        }
    }
}
